package leetcode101.tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Synhard
 * @version 1.0
 * @class Code24
 * @description 145. 二叉树的后序遍历
 * 给定一个二叉树，返回它的 后序 遍历。
 *
 * 示例:
 *
 * 输入: [1,null,2,3]
 *    1
 *     \
 *      2
 *     /
 *    3
 *
 * 输出: [3,2,1]
 *
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-06-28 7:13
 */
public class Code24 {

    public static void main(String[] args) {

    }

    public List<Integer> postorderTraversal1(TreeNode root) { // 递归写法
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }

    private void dfs(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        dfs(root.left, res);
        dfs(root.right, res);
        res.add(root.val);
    }

    public List<Integer> postorderTraversal(TreeNode root) { // 迭代写法
        if (root == null) {
            return new ArrayList<>();
        }
        Deque<TreeNode> stack = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        stack.addFirst(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peekFirst();
            if (cur != null) {
                stack.removeFirst();
                stack.addFirst(cur);
                stack.addFirst(null);
                if (cur.right != null) {
                    stack.addFirst(cur.right);
                }
                if (cur.left != null) {
                    stack.addFirst(cur.left);
                }
            } else {
                stack.removeFirst();
                res.add(stack.removeFirst().val);
            }
        }
        return res;
    }

}
